<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <!-- <el-form-item label="班级" prop="year">
        <el-select v-model="queryParams.classId" clearable filterable placeholder="请选择班级" >
          <el-option
            v-for="item in queryClazzList"
            :key="item.id"
            :label="item.title"
            :value="item.id"
            size="small">
          </el-option>
        </el-select>
      </el-form-item> -->
      <el-form-item label="音乐名称" prop="title">
        <el-input
          v-model.trim="queryParams.title"
          placeholder="请输入音乐名称"
          clearable
          size="small"
        />
      </el-form-item>
      <el-form-item label="音乐分类" prop="musicType">
          <el-select v-model="queryParams.musicType" clearable filterable placeholder="请选择音乐分类">
            <el-option
              v-for="dict in dict.type.music_type"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
              size="small">
            </el-option>
          </el-select>
        </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="warning"-->
      <!--          icon="el-icon-circle-check"-->
      <!--          size="mini"-->
      <!--          :disabled="multiple"-->
      <!--          @click="handleEnable"-->
      <!--          v-hasPermi="['base:student:enable']"-->
      <!--        >启用</el-button>-->
      <!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-circle-close"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="info"-->
      <!--          icon="el-icon-upload2"-->
      <!--          size="mini"-->
      <!--          @click="handleImport"-->
      <!--          v-hasPermi="['base:student:import']"-->
      <!--        >导入</el-button>-->
      <!--      </el-col>-->
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="info"-->
      <!--          icon="el-icon-download"-->
      <!--          size="mini"-->
      <!--          @click="handleExport"-->
      <!--          v-hasPermi="['base:student:export']"-->
      <!--        >导出</el-button>-->
      <!--      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="studentList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="音乐分类" align="center" prop="musicType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.music_type" :value="scope.row.musicType"/>
        </template>
      </el-table-column>
      <el-table-column label="音乐名称" align="center" prop="title">
        <template slot-scope="scope">
          {{scope.row.title | fileName}}
        </template>
      </el-table-column>
      <el-table-column label="音乐图片" align="center" prop="image">
        <template slot-scope="scope">
          <el-image
            style="width: 120px;height: 60px;"
            :src="scope.row.image"
            :preview-src-list="[scope.row.image]">
          </el-image>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
<!--          <el-button-->
<!--            size="mini"-->
<!--            type="text"-->
<!--            icon="el-icon-delete"-->
<!--            @click="handleDelete(scope.row)"-->
<!--          >删除</el-button>-->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改学生对话框 -->
    <el-dialog  :close-on-click-modal="false" :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="音乐分类" prop="musicType">
          <el-select v-model="form.musicType" clearable filterable placeholder="请选择音乐分类">
            <el-option
              v-for="dict in dict.type.music_type"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
              size="small">
            </el-option>
          </el-select>
        </el-form-item>
        <!--        <el-form-item label="班级" prop="classId">-->
        <!--          <el-select v-model="form.classId" clearable filterable placeholder="请选择班级">-->
        <!--            <el-option-->
        <!--              v-for="item in queryClazzList"-->
        <!--              :key="item.id"-->
        <!--              :label="item.title"-->
        <!--              :value="item.id"-->
        <!--              size="small">-->
        <!--            </el-option>-->
        <!--          </el-select>-->
        <!--        </el-form-item>-->
        <el-form-item label="音乐图片" prop="image">
          <imageUpload v-model="form.image" :limit="1" />
        </el-form-item>
        <el-form-item label="音乐" prop="filePath">
          <el-upload ref="replaceUploader" v-model="form.filePath" class="avatar-uploader"
                     :headers="upload.headers"
                     :action="upload.url"
                     :limit="1" :show-file-list="false" :on-success="handleReplaceAvatarSuccess" :beforeUpload="beforeAvatarUpload">
            <el-row>
              <el-col style="text-align: left;">
                <el-button size="small" type="primary" class="btnClick">点击上传</el-button>
              </el-col>
            </el-row>
            <el-row>
              <!--              <el-col>-->
              <!--                <audio v-if="form.file !='' && !audioFlag" :src="musicqz+form.file.path" controls> 你的浏览器不支持 <code>audio</code> 标签.</audio>-->
              <!--                <i v-else-if="form.file =='' && !audioFlag" class="el-icon-plus avatar-uploader-icon"></i> <el-progress v-if="audioFlag == true" type="line" v-bind:percentage="audioUploadPercent" style="margin-top:7px;"></el-progress>-->
              <!--              </el-col>-->
              <el-col>
                <audio v-if="form.filePath != null" :src="form.filePath" controls> 你的浏览器不支持 <code>audio</code> 标签.</audio>
              </el-col>
            </el-row>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 导入对话框 -->
    <!--    <el-dialog  :close-on-click-modal="false" :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>-->
    <!--      <el-upload-->
    <!--        ref="upload"-->
    <!--        :limit="1"-->
    <!--        accept=".xlsx, .xls"-->
    <!--        :headers="upload.headers"-->
    <!--        :action="upload.url + '?updateSupport=' + upload.updateSupport"-->
    <!--        :disabled="upload.isUploading"-->
    <!--        :on-progress="handleFileUploadProgress"-->
    <!--        :on-success="handleFileSuccess"-->
    <!--        :auto-upload="false"-->
    <!--        drag-->
    <!--      >-->
    <!--        <i class="el-icon-upload"></i>-->
    <!--        <div class="el-upload__text">-->
    <!--          将文件拖到此处，或-->
    <!--          <em>点击上传</em>-->
    <!--        </div>-->
    <!--        <div class="el-upload__tip" slot="tip">-->
    <!--          <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的学生数据-->
    <!--          <el-link type="info" style="font-size:12px" @click="importTemplate">下载模板</el-link>-->
    <!--        </div>-->
    <!--        <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</div>-->
    <!--      </el-upload>-->
    <!--      <div slot="footer" class="dialog-footer">-->
    <!--        <el-button type="primary" @click="submitFileForm">确 定</el-button>-->
    <!--        <el-button @click="upload.open = false">取 消</el-button>-->
    <!--      </div>-->
    <!--    </el-dialog>-->
  </div>
</template>

<script>
import { exportStudent, importTemplate } from "@/api/base/student";
import { selectClazz } from "@/api/base/clazz";
import { getToken } from "@/utils/auth";
import {addMusic, delMusic, editMusic, listMusic} from "@/api/base/basesystem";

export default {
  name: "Student",
  dicts: ['music_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,

      // 班级表格数据
      queryClazzList: [],

      // 学生表格数据
      studentList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,

      // 导入参数
      upload: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/common/upload"
        // url: process.env.VUE_APP_BASE_API + "/base/student/importData"
      },
      musicqz:process.env.VUE_APP_BASE_API,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: '',
        musicType:null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        musicType: [
          { required: true, message: "分类不能为空", trigger: "blur" }
        ],
        image: [
          { required: true, message: "图片不能为空", trigger: "blur" }
        ],
        filePath: [
          { required: true, message: "音频不能为空", trigger: "blur" }
        ],

      },
      //音乐
      // audioFlag:true,
      // audioUploadPercent:0,
      fileList:[],
    };
  },
  created() {
    this.getList();
    this.getQueryClazzList();
  },
  methods: {
    // 音频上传成功
    handleReplaceAvatarSuccess(res, file, fileList) {
      // this.audioFlag = false;
      // this.audioUploadPercent = 0;
      if(res.code == 200){
        this.form.filePath=res.url
        this.form.title=res.fileName
      }else{
        // this.$refs.replaceUploader.clearFiles();
        this.$refs.replaceUploader.handleRemove(file)
        this.$message.error('音频上传失败，请重新上传！');
      }
      this.$refs.replaceUploader.clearFiles();
      this.$modal.closeLoading();
    },

    //进度条
    // uploadVideoProcess(event, file, fileList) {
    //   this.audioFlag = true;
    //   this.audioUploadPercent = file.percentage.toFixed(0) * 1;
    // },
    /**上传文件限制--只能上传mp3格式的文件 */
    beforeAvatarUpload(file) {
      const isLt10M = file.size / 1024 / 1024  < 50;
      if (['audio/mp3','audio/mpeg'].indexOf(file.type) == -1) {
        this.$message.error('请上传正确的音频格式');
        return false;
      }
      if (!isLt10M) {
        this.$message.error('上传音频大小不能超过50MB哦!');
        return false;
      }else{
        this.$modal.loading("正在上传音频，请稍候...");
        this.number++;
      }


    },
    /** 查询学生列表 */
    async getList() {
      try{
        this.loading = true;
        const data=await listMusic(this.queryParams)
        this.studentList = data.rows;
        this.total = data.total;
        this.loading = false;

      }catch (e) {
        console.log(e)
      }

    },
    /** 查询班级列表 */
    getQueryClazzList() {
      this.loading = true;
      selectClazz().then(response => {
        this.queryClazzList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },


    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        musicType: null,
        image: null,
        filePath:null,
        title: null,
        schoolCode:this.$store.getters.schoolCode,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.classId = null
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加音乐";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      this.form = JSON.parse(JSON.stringify(row));
      this.open = true;
      this.title = "修改音乐";
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            editMusic(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addMusic(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除编号为"' + ids + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return delMusic(ids);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出选中的学生数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return exportStudent(queryParams);
      }).then(response => {
        this.download(response.msg);
      })
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "导入学生";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      importTemplate().then(response => {
        this.download(response.msg);
      });
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    }
  },
  filters:{
    fileName(val){
      if(val){
        let value=val.split(".")
        return value[0]
      }
    },
  },
};
</script>
